let selectionRange = null;
let iskeepSelection = false

function saveSelection() {
  if (window.getSelection) {
    var sel = window.getSelection();
    // console.log(sel)
    if (sel.getRangeAt && sel.rangeCount) {
      let range = sel.getRangeAt(0);
      let x = range.startOffset - range.endOffset
      if (x !== 0) {
        return range
      }
    }
  } else if (document.selection && document.selection.createRange) {
    return document.selection.createRange();
  }
  return null;
}

export function collectSelection() {
  selectionRange = saveSelection();

  // console.log(selectionRange)
}

export function getSelectionText() {
  if (selectionRange) {
    return selectionRange.toString()
  }
}

export function keepSelection() {
  iskeepSelection = true
}

export function isHasSelectionChange() {
  return selectionRange !== null
}

export function clearSelectionChange() {
  if (!iskeepSelection) {
    selectionRange = null
  }
  // console.log('clearSelectionChange', selectionRange)
}

export function restoreSelection(cmd) {
  // console.log('restore', iskeepSelection, selectionRange)
  if (cmd === 'clear') {
    iskeepSelection = false
  }
  let range = selectionRange
  if (range) {
    if (window.getSelection) {
      var sel = window.getSelection();
      sel.removeAllRanges();
      sel.addRange(range);
    } else if (document.selection && range.select) {
      range.select();
    }
  }
}

